﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

namespace DataBaseFactoryLib
{
    public class DataBaseFactory
    {
        private DataBaseTypeEnum? dbType;

        public DataBaseFactory()
        {
        }

        public DataBaseFactory(DataBaseTypeEnum dataBaseType)
        {
            dbType = dataBaseType;
        }

        public void SetDataBaseType(DataBaseTypeEnum dataBaseType)
        {
            dbType = dataBaseType;
        }

        private BaseDataBaseOpr CreateDataBaseOpr(DataBaseTypeEnum dataBaseType)
        {
            var baseDataClassName = GetDBClassAttribute<DBOprClassAttribute>(dataBaseType).ClassName;
            return Assembly.GetExecutingAssembly().CreateInstance(baseDataClassName) as BaseDataBaseOpr;
        }

        public BaseDataBaseOpr CreateDataBaseOpr()
        {
            if (dbType == null)
            {
                throw new Exception("数据库类型未设置");
            }
            return CreateDataBaseOpr((DataBaseTypeEnum)dbType);
        }

        private static T GetDBClassAttribute<T>(DataBaseTypeEnum dBType) where T : DBOprClassAttribute
        {
            FieldInfo fi = typeof(DataBaseTypeEnum).GetField(dBType.ToString());
            var attribute = fi.GetCustomAttribute<T>(true);
            return attribute;
        }
    }
}
